const WebSocket = require('ws');
const express = require('express');
const { fork } = require('child_process');
const port_config = require('./util/port_config');
const multer = require('multer');  // 上传文件
const dayjs = require('dayjs');
const dao = require('./dao/dao');
const dao_houtai = require('./dao/dao_houtai');
const cors = require('cors');
const app = express();
app.use(cors()); // 允许所有域名跨域请求

const port = port_config.lobby;

const url = require('url');
const clients = new Map();
const gameJS = require('./util/game');
const tuisong_serve = require('./sever_tuisong/app');

///////////////////////////////充值通道///////////////////////////////////////
const WiwiPay_recharge = require("./rechargeChannel/WiwiPay_recharge")
///////////////////////////////////充值通道///////////////////////////////////

///////////////////////////////提现通道///////////////////////////////////////
const WiwiPay_withdrawal = require("./withdrawalChannel/WiwiPay_withdrawal")
///////////////////////////////////提现通道///////////////////////////////////

const functionJS = require('./util/function');

var dailyArr = [0.409146, 0.255557, 0.136444, 0.113732, 0.068157, 0.008579, 0.004469, 0.002503, 0.001413]  //每日转盘概率
// 上传文件
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/'); // 请确保有 uploads 文件夹
    },
    filename: (req, file, cb) => {
        // 使用时间戳+原文件名作为新文件名
        cb(null, Date.now() + '-' + file.originalname);
    }
});
const upload = multer({ storage: storage }); // 上传文件
app.use('/uploads', express.static('uploads'));

// 解析 JSON 格式的请求体
app.use(express.json());
// 解析 application/x-www-form-urlencoded 格式的请求体（如果前端用的是表单提交）
app.use(express.urlencoded({ extended: true }));

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ noServer: true });

// 处理 WebSocket 连接
wss.on('connection', async (ws, req) => {
    let playerId = ws.protocol;  // 获取子协议中的 playerId
    playerId = parseInt(playerId);
    if (playerId != null && playerId !== '' && playerId !== undefined && playerId !== '0' && playerId !== 0) {
        ws.playerId = playerId;
        // 保存连接
        clients.set(playerId, ws);
    }
    let gameConfig = await dao.loadConfig();
    ws.send(JSON.stringify({ action: 'config', data: gameConfig }));

    // 获取客户端 IP 地址
    let ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    ip = functionJS.normalizeIP(ip);
    ws.ip = ip;  // 绑定到 ws 对象上

    ws.on('message', async (message) => {
        const data = JSON.parse(message);
        console.log('收到客户端信息:', data);

        if (data.action === 'login') {   //用户登录
            dao.login(data, ws.ip).then(results => {
                if (results.respCode === "SUCCESS" && results.data.player.playerId) {
                    const playerId = results.data.player.playerId;

                    // 检查是否已经有该账号的连接
                    if (clients.has(playerId)) {
                        ws.send(JSON.stringify({
                            action: 'login',
                            data: {
                                respCode: "FAIL",
                                message: "This account is logged in else where."
                            }
                        }));
                        return; // 中止后续操作
                    }

                    // 未登录，绑定连接
                    clients.set(playerId, ws);
                    ws.playerId = playerId;

                    ws.send(JSON.stringify({
                        action: 'login',
                        data: results
                    }));
                } else {
                    // 登录失败，账号或密码错误等
                    ws.send(JSON.stringify({
                        action: 'login',
                        data: results
                    }));
                }
            }).catch(error => {
                console.log('登录失败:', error);
                ws.send(JSON.stringify({
                    action: 'login',
                    data: {
                        respCode: "FAIL",
                        message: error.message
                    }
                }));
            });
        } else if (data.action === 'reg') {  // 用户注册
            let freeCoin = 0.00;
            for (let i = 0; i < gameConfig.data.config.length; i++) {
                const element = gameConfig.data.config[i];
                if (element.name == "freeCoin") {
                    freeCoin = element.value;
                }
            }
            data.coin = freeCoin;
            dao.register(data).then(results => {
                ws.send(JSON.stringify({ action: 'reg', data: results }));
            }).catch(error => {
                console.log('注册失败:', error);
                ws.send(JSON.stringify({ action: 'reg', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'changeHead') { // 修改头像
            dao.changeHead(data).then(results => {
                ws.send(JSON.stringify({ action: 'changeHead', data: results }));
            }).catch(error => {
                console.log('修改头像失败:', error);
                ws.send(JSON.stringify({ action: 'changeHead', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'changePsw') { // 修改密码
            dao.changePsw(data).then(results => {
                ws.send(JSON.stringify({ action: 'changePsw', data: results }));
            }).catch(error => {
                console.log('修改密码失败:', error);
                ws.send(JSON.stringify({ action: 'changePsw', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'getBetRecord') { // 获取投注稽核
            let result = await dao.getBetRecord(data);
            if (result.respCode == "SUCCESS") {
                ws.send(JSON.stringify({ action: 'getBetRecord', data: result }));
            } else {
                ws.send(JSON.stringify({ action: 'getBetRecord', data: { respCode: "FAIL", message: result.message } }));
            }
        } else if (data.action === 'getBetHistory') {  // 获取投注记录
            let result = await dao.getBetHistory(data);
            if (result.respCode == "SUCCESS") {
                ws.send(JSON.stringify({ action: 'getBetHistory', data: result }));
            } else {
                ws.send(JSON.stringify({ action: 'getBetHistory', data: { respCode: "FAIL", message: result.message } }));
            }
        } else if (data.action === 'loginOut') {  // 用户登出
            let result = await dao.userLoginOut(data.playerId);
            if (result.respCode == "SUCCESS") {
                console.log(`玩家 ${data.playerId} 登出`);
                clients.delete(data.playerId);
            }
        } else if (data.action === 'readEmail') {  //已读邮件
            dao.readEmail(data).then(results => {
                ws.send(JSON.stringify({ action: 'readEmail', data: results }));
            }).catch(error => {
                console.log('已读邮件失败:', error);
                ws.send(JSON.stringify({ action: 'readEmail', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'receiveEmail') {   // 领取邮件
            dao.receiveEmail(data).then(async (results) => {
                ws.send(JSON.stringify({ action: 'receiveEmail', data: results }));
            }).catch(error => {
                console.log('领取邮件失败:', error);
                ws.send(JSON.stringify({ action: 'receiveEmail', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'deleteEmail') { // 处理删除邮件
            dao.deleteEmail(data).then(async (results) => {
                ws.send(JSON.stringify({ action: 'deleteEmail', data: results }));
            }).catch(error => {
                console.log('删除邮件失败:', error);
                ws.send(JSON.stringify({ action: 'deleteEmail', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'getDaily') {  //获取每日转盘数据
            dao.getDaily(data.playerId).then(async (result) => {
                ws.send(JSON.stringify({ action: 'getDaily', data: { respCode: "SUCCESS", data: result } }));
            }).catch(error => {
                console.log('获取每日转盘数据失败:', error);
                ws.send(JSON.stringify({ action: 'getDaily', data: { respCode: "FAIL", message: error.message } }));
            });

        } else if (data.action === 'daily') {  // 处理每日转盘
            let coinArr = [5, 8, 15, 18, 30, 38, 58, 88, 128]
            let coinPan = [5, 30, 58, 5, 8, 88, 18, 5, 15, 38, 5, 128]
            let coin = functionJS.weightedRandom(dailyArr, coinArr)

            let indexes = coinPan
                .map((val, idx) => val === coin ? idx : -1)
                .filter(idx => idx !== -1);

            let zhuan = indexes[Math.floor(Math.random() * indexes.length)];

            let ret = {
                coin: coin,
                zhuan: zhuan,
            }
            dao.updateDaily(data.playerId, coin, zhuan).then(async () => {
                ws.send(JSON.stringify({ action: 'daily', data: { respCode: "SUCCESS", data: ret } }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'daily', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'getRedeemConfig') { //获取提现配置
            dao.getRedeemConfig(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'getRedeemConfig', data: { respCode: "SUCCESS", data: ret } }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getRedeemConfig', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'changeCashTag') { // 处理CashTag
            dao.changeCashTag(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'changeCashTag', data: { respCode: "SUCCESS", data: ret } }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'changeCashTag', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'quickStart') {   // 处理快速登录
            dao.quickStart(data, ws.ip).then(async (ret) => {
                if (ret.respCode === "SUCCESS") {
                    const playerId = ret.data.player.playerId;

                    // 同号检测
                    if (clients.has(playerId)) {
                        ws.send(JSON.stringify({
                            action: 'quickStart',
                            data: {
                                respCode: "FAIL",
                                message: "This account is logged in else where."
                            }
                        }));
                        return; // 不再继续处理
                    }

                    // 绑定连接
                    clients.set(playerId, ws);
                    ws.playerId = playerId;
                }
                // 保持原有返回格式
                ws.send(JSON.stringify({ action: 'quickStart', data: { respCode: "SUCCESS", data: ret } }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'quickStart', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'bindAccount') {   // 处理绑定账号
            dao.bindAccount(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'bindAccount', data: ret }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'bindAccount', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'getKefuUrl') {  // 处理获取客服链接
            dao.getKefuUrl(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'getKefuUrl', data: ret }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getKefuUrl', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'getEventData') {   // 处理获取活动数据
            dao.getEventData(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'getEventData', data: ret }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getEventData', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'getRechargeChannel') {  // 处理获取充值渠道
            dao.getRechargeChannel(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'getRechargeChannel', data: ret }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getRechargeChannel', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'changeIsOK') {  //修改充值订单的isOK字段
            dao.changeIsOK(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'changeIsOK', data: ret }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'changeIsOK', data: { respCode: "FAIL", message: error.message } }));
            });
        } else if (data.action === 'getRechargeRecord') {  // 获取玩家充值记录
            dao.getRechargeRecord(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'getRechargeRecord', data: ret }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getRechargeRecord', data: { respCode: "FAIL", message: error.message } }));
            })
        } else if (data.action === 'getVipInfo') {  // 获取玩家VIP信息
            dao.getVipInfo(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'getVipInfo', data: ret }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getVipInfo', data: { respCode: "FAIL", message: error.message } }));
            })
        } else if (data.action === 'receiveVipBonus') { //领取会员奖励
            const playerId = data.playerId;
            dao.receiveVipBonus(data).then(async (ret) => {
                ws.send(JSON.stringify({ action: 'receiveVipBonus', data: ret }));
                dao.getPlayerMails(playerId)
                    .then(mailList => {
                        functionJS.broadcastPlayerMail(clients, playerId, mailList, true);
                    })
                    .catch(error => {
                        console.error('查询邮件出错:', error);
                        res.status(500).json({ success: false, message: 'Internal Server Error' });
                    });
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'receiveVipBonus', data: { respCode: "FAIL", message: error.message } }));
            })
        } else if (data.action === 'getTotalRecharge') {  // 获取总充值金额
            dao.getTotalRecharge(data).then(async (result) => {
                ws.send(JSON.stringify({ action: 'getTotalRecharge', data: result }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getTotalRecharge', data: { respCode: "FAIL", message: error.message } }));
            })
        } else if (data.action === 'bindAgent') {   // 处理代理绑定
            if (data.type == "agentId") {
                dao.bindAgent(data).then(async (result) => {
                    ws.send(JSON.stringify({ action: 'bindAgent', data: result }));
                }).catch(async (error) => {
                    ws.send(JSON.stringify({ action: 'bindAgent', data: { respCode: "FAIL", message: error.message } }));
                })
            } else if (data.type == "inviterId") {
                dao.bindInviter(data).then(async (result) => {
                    ws.send(JSON.stringify({ action: 'bindAgent', data: result }));
                }).catch(async (error) => {
                    ws.send(JSON.stringify({ action: 'bindAgent', data: { respCode: "FAIL", message: error.message } }));
                })
            }
        } else if (data.action === "getFirstRechargeInfo") { // 获取首充信息
            dao.getFirstRechargeInfo(data).then(async (result) => {
                ws.send(JSON.stringify({ action: 'getFirstRechargeInfo', data: result }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getFirstRechargeInfo', data: { respCode: "FAIL", message: error.message } }));
            })
        } else if (data.action === "getOrderRecord") {  // 获取订单记录
            dao.getOrderRecord(data).then(async (result) => {
                ws.send(JSON.stringify({ action: 'getOrderRecord', data: result }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getOrderRecord', data: { respCode: "FAIL", message: error.message } }));
            })
        } else if (data.action === "getPlayerCoin") { // 获取玩家金币
            let playerId = data.playerId;
            dao.getPlayerCoin(playerId).then(async (result) => {
                ws.send(JSON.stringify({ action: 'getPlayerCoin', data: result }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getPlayerCoin', data: { respCode: "FAIL", message: error.message } }));
            })
        } else if (data.action === 'getAllSons') { //处理所有子玩家
            dao.getAllSons(data).then(async (result) => {
                ws.send(JSON.stringify({ action: 'getAllSons', data: result }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getAllSons', data: { respCode: "FAIL", message: error.message } }));
            })
        } else if (data.action === 'getRechargeSon') {   //获取一级充值的玩家
            dao.getRechargeSon(data).then(async (result) => {
                ws.send(JSON.stringify({ action: 'getRechargeSon', data: result }));
            }).catch(async (error) => {
                ws.send(JSON.stringify({ action: 'getRechargeSon', data: { respCode: "FAIL", message: error.message } }));
            })
        }
    });

    ws.on('error', (error) => {
        console.error('WebSocket error:', error);

        ws.close();  //遇到错误主动断开链接，如果客户端在线的话会重连
    });

    ws.on('close', () => {
        if (ws.playerId) {
            clients.delete(ws.playerId);
            console.log('玩家' + ws.playerId + '断开连接');
            dao.changePlayerStatus(ws.playerId, 0)
        }
    });
});

// 设置 HTTP 服务，以便扩展功能（如 REST API）
app.server = app.listen(port, () => {
    console.log("✅大厅服务器启动成功，端口：", port);
});

// 使 WebSocket 和 HTTP 服务共用同一个端口
app.server.on('upgrade', (request, socket, head) => {
    wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request);
    });
});

//开启推送大奖
tuisong_serve.startPushBigWin(wss);

// 监听 POST 请求 //后台登录
app.post('/login', (req, res) => {
    const data = req.body;
    dao_houtai.login(data).then(results => {
        res.json({ success: true, data: results }); // 返回 HTTP 响应
    }).catch(error => {
        console.error('Login error:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
});

//获取玩家列表
app.post('/getPlayerList', (req, res) => {
    const data = req.body;
    dao_houtai.getPlayerList(data).then(results => {
        res.json({ success: true, data: results }); // 返回 HTTP 响应
    }).catch(error => {
        console.error('Login error:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
});

//修改玩家信息
app.post('/updatePlayer', (req, res) => {
    const data = req.body; // 假设 data 中包含 playerId 和 coins
    dao_houtai.updatePlayer(data).then(results => {
        res.json({ success: true, data: results }); // 返回 HTTP 响应

        // 通过 WebSocket 通知对应玩家
        const playerId = data.playerId; // 假设请求体中包含 playerId
        const ws = clients.get(playerId);
        if (ws) {
            ws.send(JSON.stringify({
                action: 'updatePlayerInfo',
                data: data // 假设 results 中包含更新后的金币
            }));
        } else {
            console.log(`玩家 ${playerId} 未连接，无法推送金币更新`);
        }
    }).catch(error => {
        console.error('Update player error:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
});


//获取游戏信息
app.post('/getGameInfo', (req, res) => {
    dao_houtai.getGameInfo().then(results => {
        res.json({ success: true, data: results }); // 返回 HTTP 响应
    }).catch(error => {
        console.error('Login error:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    })
})


//修改游戏状态updateGameStatus
app.post('/updateGameStatus', (req, res) => {
    const data = req.body;
    dao_houtai.updateGameStatus(data).then(results => {
        res.json({ success: true, data: results }); // 返回 HTTP 响应
        const message = JSON.stringify({
            action: 'gameStatusUpdated',
            data: data
        });
        // 遍历 clients Map，向每个连接发送消息
        clients.forEach((ws, playerId) => {
            try {
                if (ws.readyState === ws.OPEN) { // 检查连接是否打开
                    ws.send(message);
                }
            } catch (error) {
                console.error(`Failed to send to player ${playerId}:`, error);
            }
        });
    }).catch(error => {
        console.error('Login error:', error);
        res.status(500).json({ success: false, message: 'Internal ServerError' });
    })
})

//修改游戏难度updateGameDifficulty
app.post('/updateGameDifficulty', async (req, res) => {
    const data = req.body;
    let results = await dao_houtai.updateGameDifficulty(data)
    console.log(results);
    res.json(results);
    if (results.success) {
        for (let i = 0; i < gameJS.gameJS.length; i++) {
            const element = gameJS.gameJS[i];
            element.changeGameLevel(data.level)
        }
    }
})

//获取跑马灯信息
app.post('/getMessage', (req, res) => {
    dao_houtai.getMessage().then(results => {
        res.json({ success: true, data: results }); // 返回 HTTP 响应
    }).catch(error => {
        console.error('error:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    })
})

//修改跑马灯信息
app.post('/updateMessage', (req, res) => {
    dao_houtai.updateMessage(req).then(() => {
        // 更新成功后，再查一次全部消息
        dao_houtai.getMessage().then(results => {
            res.json({ success: true, data: results }); // 返回给请求客户端

            // 广播给所有在线客户端
            const message = JSON.stringify({
                action: 'updateMessageList',
                data: results
            });

            clients.forEach((ws, playerId) => {
                try {
                    if (ws.readyState === ws.OPEN) {
                        ws.send(message);
                    }
                } catch (error) {
                    console.error(`Failed to send to player ${playerId}:`, error);
                }
            });

        }).catch(error => {
            console.error('error getting updated message list:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
    }).catch(error => {
        console.error('error:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    })
})

//添加跑马灯信息
app.post('/addMessage', (req, res) => {
    dao_houtai.addMessage(req).then(() => {
        // 添加成功后获取所有消息
        dao_houtai.getMessage().then(results => {
            res.json({ success: true, data: results }); // 返回 HTTP 响应

            // 推送给所有在线玩家
            const message = JSON.stringify({
                action: 'updateMessageList',
                data: results
            });

            clients.forEach((ws, playerId) => {
                try {
                    if (ws.readyState === ws.OPEN) {
                        ws.send(message);
                    }
                } catch (error) {
                    console.error(`Failed to send to player ${playerId}:`, error);
                }
            });

        }).catch(error => {
            console.error('error getting updated message list:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });

    }).catch(error => {
        console.error('error:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
});

// 删除跑马灯信息
app.post('/deleteMessage', (req, res) => {
    const { id } = req.body; // 前端传入要删除的消息 ID

    if (!id) {
        return res.status(400).json({ success: false, message: 'Missing message ID' });
    }

    dao_houtai.deleteMessage(id).then(() => {
        // 删除成功后获取最新消息列表
        dao_houtai.getMessage().then(results => {
            res.json({ success: true, data: results }); // 返回更新后的列表

            // 推送给所有在线客户端
            const message = JSON.stringify({
                action: 'updateMessageList',
                data: results
            });

            clients.forEach((ws, playerId) => {
                try {
                    if (ws.readyState === ws.OPEN) {
                        ws.send(message);
                    }
                } catch (error) {
                    console.error(`Failed to send to player ${playerId}:`, error);
                }
            });

        }).catch(error => {
            console.error('Error getting updated message list:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });

    }).catch(error => {
        console.error('Error deleting message:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
});

// 根据玩家ID获取邮件列表
app.post('/getPlayerMails', (req, res) => {
    const data = req.body;
    dao_houtai.getPlayerMails(data).then(results => {
        res.json({ success: true, data: results });
    }).catch(error => {
        console.error('获取邮件出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
});

// 发送邮件
app.post('/sendPlayerMail', (req, res) => {
    let playerId = req.body.playerId;
    let agentId = req.body.agentId;

    if (!playerId) {
        return res.status(400).json({ success: false, message: 'Missing playerId' });
    }
    if (!agentId) {
        return res.status(400).json({ success: false, message: 'Missing agentId' });
    }

    dao_houtai.addPlayerMail(req.body)
        .then(result => {
            if (result.respCode !== "SUCCESS") {
                // 手动抛出错误中断链式调用
                throw new Error(result.message || '添加邮件失败');
            }
            // 邮件添加成功后再获取邮件列表
            return dao.getPlayerMails(req.body.playerId);
        })
        .then(mailList => {
            res.json({ success: true, data: mailList });
            functionJS.broadcastPlayerMail(clients, req.body.playerId, mailList); // 广播
        })
        .catch(error => {
            console.error('发送邮件出错:', error);
            res.status(500).json({ success: false, message: error.message || 'Internal Server Error' });
        });
});

//查询配置
app.post('/getConfigData', (req, res) => {
    dao_houtai.getConfigData().then(result => {
        res.json({ success: true, data: result });
    }).catch(error => {
        console.error('查询配置出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
});


//修改配置
app.post('/updateConfigData', (req, res) => {
    dao_houtai.updateConfigData(req.body).then(result => {
        res.json({ success: true, data: result });
    }).catch(error => {
        console.error('修改配置出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
});

//查新提现路径配置
app.post('/getRedeemConfig', (req, res) => {
    let data = req.body;
    dao_houtai.getRedeemConfig(data).then(result => {
        res.json({ success: true, data: result });
    }).catch(error => {
        console.error('查询提现路径配置出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
})

//新建提现路径
app.post('/addRedeemConfig', (req, res) => {
    dao_houtai.addRedeemConfig(req.body).then(result => {
        res.json({ success: true, data: result });
    }).catch(error => {
        console.error('新建提现路径出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
})

//修改提现路径
app.post('/updateRedeemConfig', (req, res) => {
    dao_houtai.updateRedeemConfig(req.body).then(result => {
        res.json({ success: true, data: result });
    }).catch(error => {
        console.error('修改提现路径出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
})

//获取客服列表
app.post('/getCustomerService', (req, res) => {
    let data = req.body;
    dao_houtai.getCustomerService(data).then(result => {
        res.json({ success: true, data: result });
    }).catch(error => {
        console.error('获取客服列表出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
})

//修改客服链接
app.post('/updateCustomerService', (req, res) => {
    dao_houtai.updateCustomerService(req.body).then(result => {
        res.json({ success: true, data: result });
    }).catch(error => {
        console.error('修改客服链接出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
})


//获取活动列表
app.post('/getEvent', (req, res) => {
    dao_houtai.getEvent().then(result => {
        res.json({ success: true, data: result });
    }).catch(error => {
        console.error('获取活动列表出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
})


//添加活动
app.post('/addEvent', upload.single('img'), (req, res) => {
    const eventData = req.body;
    req.body.startTime = dayjs(req.body.startTime).format('YYYY-MM-DD HH:mm:ss');
    if (req.body.stopTime != '') {
        req.body.stopTime = dayjs(req.body.stopTime).format('YYYY-MM-DD HH:mm:ss');
    } else {
        req.body.stopTime = null;
    }
    const fileInfo = req.file; // 上传的图片信息

    // 可以将文件路径加入 eventData 中保存数据库
    eventData.imageUrl = fileInfo ? fileInfo.path : null;

    dao_houtai.addEvent(eventData)
        .then(result => {
            res.json({ success: true, data: result });
        })
        .catch(error => {
            console.error('添加活动出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
});

//修改活动
app.post('/updateEvent', upload.single('img'), (req, res) => {
    const eventData = req.body;
    req.body.startTime = dayjs(req.body.startTime).format('YYYY-MM-DD HH:mm:ss');
    if (req.body.stopTime != '') {
        req.body.stopTime = dayjs(req.body.stopTime).format('YYYY-MM-DD HH:mm:ss');
    } else {
        req.body.stopTime = null;
    }
    const fileInfo = req.file; // 上传的图片信息

    // 可以将文件路径加入 eventData 中保存数据库
    eventData.imageUrl = fileInfo ? fileInfo.path : null;

    dao_houtai.updateEvent(eventData)
        .then(result => {
            res.json({ success: true, data: result });
        })
        .catch(error => {
            console.error('添加活动出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
});

//获取充值通道配置
app.post('/getRechargeConfig', (req, res) => {
    let data = req.body;
    dao_houtai.getRechargeConfig(data)
        .then(result => {
            res.json({ success: true, data: result });
        })
        .catch(error => {
            console.error('获取充值通道配置出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
});

//更新充值通道配置
app.post('/updateRechargeChannel', (req, res) => {
    dao_houtai.updateRechargeChannel(req.body)
        .then(result => {
            res.json({ success: true, data: result });
        })
        .catch(error => {
            console.error('更新充值通道配置出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
});


//查询充值订单接口
app.post('/getRechargeOrder', (req, res) => {
    dao_houtai.getRechargeOrder(req.body)
        .then(result => {
            res.json({ success: true, data: result });
        })
        .catch(error => {
            console.error('查询充值订单出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
})


//后台主页数据面板
app.post('/getAllInfo', (req, res) => {
    let data = req.body;
    dao_houtai.getAllInfo(data)
        .then(result => {
            res.json({ success: true, data: result });
        })
        .catch(error => {
            console.error('查询数据出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
})


//获取在线人数
app.post('/getOnlineCount', (req, res) => {

    dao_houtai.getOnlineCount()
        .then(result => {
            res.json({ success: true, data: result });
        })
        .catch(error => {
            console.error('查询数据出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
})


//查询代理
app.post("/getAgentList", (req, res) => {
    let data = req.body;
    dao_houtai.getAgentList(data)
        .then(result => {
            res.json(result);
        })
        .catch(error => {
            console.error('查询代理出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
});

//查询代理id和昵称
app.post("/getAgentList2", (req, res) => {
    let data = req.body;
    dao_houtai.getAgentList2(data)
        .then(result => {
            res.json(result);
        })
        .catch(error => {
            console.error('查询代理出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
});

//添加代理
app.post("/addAgent", (req, res) => {
    let data = req.body;
    dao_houtai.addAgent(data)
        .then(result => {
            res.json(result);
        })
        .catch(error => {
            console.error('添加代理出错:', error);
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        });
});

//获取代理详细信息
app.post("/getAgentAnalysis", (req, res) => {
    let data = req.body;
    dao_houtai.getAgentAnalysis(data).then(result => {
        res.json({ success: true, result });
    }).catch(error => {
        console.error('查询代理出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    });
})

//获取提现订单
app.post("/getRedeemOrder", (req, res) => {
    let data = req.body;
    dao_houtai.getRedeemOrder(data).then(result => {
        res.json({ success: true, result });
    }).catch(error => {
        console.error('查询提现订单出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    })
})

//代理修改密码
app.post("/changeAgentPassword", (req, res) => {
    let data = req.body;
    dao_houtai.changeAgentPassword(data).then(result => {
        res.json({ success: true, result });
    }).catch(error => {
        console.error('修改密码出错:', error);
        res.status(500).json({ success: false, message: 'Internal Server Error' });
    })
})



// 充值接口
app.post('/recharge', (req, res) => {
    const data = req.body;
    const rechargeWay = data.rechargeWay;   //充值平台

    let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.ip;
    ip = functionJS.normalizeIP(ip);

    if (rechargeWay == "WiwiPay") {
        WiwiPay_recharge.startRecharge(data, ip).then(result => {
            console.log(result);
            res.json(result);
        });
    }
})

// 充值回调
app.post('/rechargeNotify', (req, res) => {
    let orderId = req.body.mchOrderNo;
    dao.rechargeCallback(orderId).then(result => {
        const playerId = result.playerId;
        if (result.success) {
            dao.getPlayerMails(playerId)
                .then(mailList => {
                    functionJS.broadcastPlayerMail(clients, playerId, mailList, true);
                })
                .catch(error => {
                    console.error('查询邮件出错:', error);
                    res.status(500).json({ success: false, message: 'Internal Server Error' });
                });
        }
    });
    res.send("success");
});


//兑换接口
app.post('/redeem', async (req, res) => {
    try {
        const data = req.body;
        let amount = parseInt(data.amount);
        //检查提现资格
        let jiheData = await dao.getBetRecord(data);
        jiheData = jiheData.data;
        for (let i = 0; i < jiheData.length; i++) {
            const element = jiheData[i];
            if (!element.success) {
                let data = {
                    code: 14250   //提现资格不足
                }
                res.json(data);
                return;
            }
        }

        //检查余额
        let playerCoin = await dao.getPlayerCoin(data.playerId);
        if (playerCoin / 100 < amount) {
            let data = {
                code: 14258  //余额不足
            }
            res.json(data);
            return;
        }

        let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.ip;
        ip = functionJS.normalizeIP(ip);

        if (data.redeemWay == "WiwiPay") {
            WiwiPay_withdrawal.startWithdraw(data, ip).then(result => {
                console.log(result);
                res.json(result);
            });
        }
    } catch (error) {
        console.error('redeem接口异常:', error);
        res.status(500).json({ error: 'Server error' });
    }
});


//兑换回调
app.post('/withdrawNotify', (req, res) => {
    let data = req.body;
    dao.withdrawalCallback(data).then(result => {
        const playerId = result.playerId;
        if (result.success) {
            dao.getPlayerMails(playerId)
                .then(mailList => {
                    functionJS.broadcastPlayerMail(clients, playerId, mailList, false);
                })
                .catch(error => {
                    console.error('查询邮件出错:', error);
                    res.status(500).json({ success: false, message: 'Internal Server Error' });
                });
        }
    })
    res.json("success");

})





